package dev.alm.ggzxservice.controller;

import dev.alm.ggzxservice.common.Result;
import dev.alm.ggzxservice.entity.User;
import dev.alm.ggzxservice.service.UserService;
import dev.alm.ggzxservice.utils.JedisUtil;
import dev.alm.ggzxservice.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.HashMap;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("add")
    public Result addUser(@RequestBody User user) {
        User user1 = userService.addUser(user);
        Result result = new Result();
        if (user1 == null) {
            result.fail();
            return result;
        }
        result.success();
        result.setData(user1);
        return result;
    }

    @PostMapping("logout")
    public Result userLogout(@RequestHeader("token") String token) {
        // 通过 token 解析出 username
        String username = JwtUtils.parseJwtToken(token);
        Result r = new Result();
        Jedis jedis = JedisUtil.getJedisPoolInstance().getResource();
        jedis.del(username);
        JedisUtil.release(jedis);
        r.success();
        r.setMessage("退出成功");
        return r;
    }

    @PostMapping("login")
    public Result userLogin(@RequestBody User user) {
        User user1 = userService.userLogin(user);
        Result r = new Result();
        if (user1 == null) {
            r.fail();
            r.setMessage("用户名或密码错误");
            return r;
        }
        // 存入 redis 缓存
        Jedis jedis = JedisUtil.getJedisPoolInstance().getResource();
        // 先尝试寻找 redis 中是否已经有此用户的 token 存在
        String token = jedis.get(user1.getUsername());
        if (token == null) {
            token = JwtUtils.generateJwtToken(user1.getUsername());
            jedis.set(user1.getUsername(), token);
            jedis.expire(user1.getUsername(), 3600);
        }
        JedisUtil.release(jedis);
        r.success();
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user1);
        r.setData(map);
        return r;
    }

}
